import Axios from 'axios';
import Config from '../config';

import { Toast } from 'vant';

// 创建service
const service = Axios.create({
  headers: {
    'Accept': '*/*'
  },
  timeout: Config.timeout
});

service.defaults.retry = Config.requestRetry;
service.defaults.retryDelay = Config.requestRetryDelay;

window.LoadingInstance = null;

// 配置统一 request拦截
service.interceptors.request.use(
  config => {
    // 统一请求加载提示
    window.LoadingInstance = Toast.loading({
      mask: true,
      message: '加载中...'
    });
    // token验证在这里
    // config.headers['Authorization'] =  'setToken';
    return config;
  },
  error => {
    Promise.reject(error);
  }
);

// 配置统一 response拦截
service.interceptors.response.use(
  res => {
    // 统一请求关闭loading
    if (window.LoadingInstance) {
      window.LoadingInstance.clear();
    }
    if (res.status !== 200) {
      Toast('数据返回出错');
      return Promise.reject(new Error('响应非200！'));
    } else {
      // 统一处理错误code
      if (res.data.code !== 0) {
        Toast(res.data.msg);
        return Promise.reject(res.data.msg);
      }
      return res.data.data;
    }
  },
  error => {
    if (window.LoadingInstance) {
      window.LoadingInstance.clear();
    }
    Toast('网络错误');
    return Promise.reject(error);
  }
);

//
export default function(url, data = {}, type = 'GET') {
  return new Promise(function(resolve, reject) {
    // 执行异步ajax请求
    let promise;
    if (type === 'GET') {
      // 准备url query参数数据
      let dataStr = ''; // 数据拼接字符串
      Object.keys(data).forEach(key => {
        dataStr += key + '=' + data[key] + '&';
      });
      if (dataStr !== '') {
        dataStr = dataStr.substring(0, dataStr.lastIndexOf('&'));
        url = url + '?' + dataStr;
      }
      // 发送get请求
      promise = service.get(url);
    } else {
      // 发送post请求
      promise = service.post(url, data);
    }
    promise.then(function(response) {
      // 成功了调用resolve()
      resolve(response);
    }).catch(function(error) {
      // 失败了调用reject()
      reject(error);
    });
  });
}
